package com.shansun.event.redis
import com.redis.Subscriber
import com.redis.RedisClient
import com.redis.Register
import com.redis.Subscribe
import com.redis.Unsubscribe
import com.redis.PubSubMessage
import com.redis.S
import com.redis.U
import com.redis.M
import javax.crypto.Cipher.r

/**
 * <p></p>
 * @author:     lanbo <br>
 * @version:    1.0  <br>
 * @date:   	2012-4-16
 */
object Sub {
    println("starting subscription service ..")
    val r = new RedisClient("localhost", 6379)
    val s = new Subscriber(r)
    s.start
    s ! Register(callback)

    def sub(channels: String*) = {
        s ! Subscribe(channels.toArray)
    }

    def ubsub(channels: String*) = {
        s ! Unsubscribe(channels.toArray)
    }

    def callback(pubsub: PubSubMessage) = pubsub match {
        case S(channel, no) => println("subscribed to " + channel + " and count = " + no)
        case U(channel, no) => println("unsubscribed from " + channel + " and count = " + no)
        case M(channel, msg) =>
            msg match {
                // exit will unsubscribe from all channels and stop subscription service
                case "exit" =>
                    println("unsubscribe all ..")
                    r.unsubscribe

                // message "+x" will subscribe to channel x
                case x if x startsWith "+" =>
                    val s: Seq[Char] = x
                    s match {
                        case Seq('+', rest @ _*) => r.subscribe(rest.toString) { m => }
                    }

                // message "-x" will unsubscribe from channel x
                case x if x startsWith "-" =>
                    val s: Seq[Char] = x
                    s match {
                        case Seq('-', rest @ _*) => r.unsubscribe(rest.toString)
                    }

                // other message receive
                case x =>
                    println("received message on channel " + channel + " as : " + x)
            }
    }
    
    def main(args: Array[String]) {
    	Sub
    }
}